package com.eurasia.firstapp.resources;

import com.eurasia.firstapp.commands.CreateUserCommand;
import com.eurasia.firstapp.commands.UpdateUserCommand;
import com.eurasia.firstapp.entities.User;
import com.eurasia.firstapp.exceptions.BusinessException;
import com.eurasia.firstapp.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api")
public class UserResource {
    @Autowired
    private UserService userService;

    @PostMapping("users/register")
    public ResponseEntity register(@RequestBody CreateUserCommand createUserCommand) throws BusinessException {
        User user = userService.register(createUserCommand.getUsername(), createUserCommand.getPassword());
        return new ResponseEntity(user, HttpStatus.CREATED);
    }

    @GetMapping("users/login")
    public ResponseEntity login(@RequestParam String username,
                                @RequestParam String password) throws BusinessException {
        User user = userService.login(username, password);
        return ResponseEntity.ok(user);
    }


    @GetMapping("users/{id}")
    public ResponseEntity findUser(@PathVariable Long id) throws BusinessException {
        User user = userService.findUserById(id);
        return ResponseEntity.ok(user);
    }

    @DeleteMapping("users/{id}")
    public ResponseEntity deleteUser(@PathVariable Long id) throws BusinessException {
        userService.deleteUserById(id);
        return ResponseEntity.noContent().build();
    }


    @PutMapping("users/{id}")
    public ResponseEntity updateUser(
        @PathVariable Long id,
        @RequestBody UpdateUserCommand updateUserCommand) throws BusinessException {
        userService.updateUser(id, updateUserCommand.getPassword());
        return ResponseEntity.ok().build();
    }

    @GetMapping("users")
    public ResponseEntity findUsers() throws BusinessException {
        List<User> users = userService.findUsers();
        return ResponseEntity.ok(users);
    }
}
